'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 清除军功宝箱CD
 * @author agl
 */

var _ = require('lodash');
var moment = require('moment');
var async = require('async');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var PlayerManager = require('../../../../libs/playerManager');
var taskService = require('../../../../services/taskService');
var buildService = require('../../../../services/buildService');
var roleService = require('../../../../services/roleService');

module.exports = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['pvp', 'role', 'bag', 'build', 'task', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var pvp_model = player_manager.pvp;
                var remain_time = pvp_model.open_honor_box_tm - moment().unix();

                if (remain_time <= 0) {
                    return next(null, {
                        code: Code.PVP_NOT_IN_HONOR_BOX_CD
                    });
                }

                var sub_diamond = buildService.getDirectProduceDiamond(remain_time);
                if (!roleService.subDiamond(player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_HONOR_BOX_CLEAR_CD, sub_diamond)) {
                    return next(null, {
                        code: Code.USER_DIAMOND_NOT_ENOUGH
                    });
                }

                pvp_model.open_honor_box_tm = 0;

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
            });
        }
    );
};
